import { AdminLayout } from '@/components/Layout';
import Head from 'next/head';

import { useCallback, useEffect, useState, useRef } from 'react';
import type { Category } from '@prisma/client';
import { requestMsg } from '@/components/server/utils/request';
import type { Data, DataItem } from '@/pages/api/post/list';
import type { Data as CatData } from '@/pages/api/post/categories/list';
import { FormattedMessage, useIntl } from 'react-intl';
import { getLangByIntl } from '@/components/utils/locale';
import { ProList } from '@ant-design/pro-components';
import type { ActionType } from '@ant-design/pro-components';
import { Space, Tag, Button, Popconfirm } from 'antd';
import { useRouter } from 'next/router';

export default function Index() {
  const router = useRouter();
  const intl = useIntl();
  const lang = getLangByIntl(intl);
  const ref = useRef<ActionType>();
  const handleDelete = (id: number) => {
    requestMsg<Data>('/api/post/delete', {
      method: 'post',
      data: { id },
    })
      .then((data) => {
        console.log(data);
        ref.current?.reload();
      })
      .catch((err) => {
        console.error(err);
      });
  };
  const [cats, setCats] = useState<Record<number, { text: string }>>();
  const fetchCatCallBack = useCallback(() => {
    const fetchCatData = (page: number, size: number) => {
      requestMsg<CatData>('/api/post/categories/list', {
        method: 'post',
        data: { page, size, catId: 1 },
        lang,
      }).then((res) => {
        const data: Record<number, { text: string }> = {};
        res.categories?.map((item) => {
          data[item.id] = { text: item.cat };
        });
        console.log(data);
        setCats(data);
      });
    };
    fetchCatData(1, 100);
  }, [lang]);
  useEffect(() => {
    fetchCatCallBack();
  }, []);
  return (
    <>
      <Head>
        <link
          rel="shortcut icon"
          type="image/x-icon"
          href="https://unpkg.byted-static.com/latest/byted/arco-config/assets/favicon.ico"
        />
        <title>{intl.formatMessage({ id: 'post.list' })}</title>
      </Head>
      <ProList<DataItem>
        rowKey="name2"
        headerTitle={intl.formatMessage({ id: 'post.list' })}
        itemCardProps={{}}
        itemLayout="vertical"
        actionRef={ref}
        metas={{
          title: {
            dataIndex: 'title',
            title: intl.formatMessage({ id: 'post.title' }),
          },
          description: {
            dataIndex: 'desc',
            search: false,
          },
          content: {
            search: false,
            render: (text, row) => {
              return (
                <>
                  <Space>
                    {row.categories.map((value) => {
                      return (
                        <>
                          <Tag>{value.category.cat}</Tag>
                        </>
                      );
                    })}
                  </Space>
                </>
              );
            },
          },
          status: {
            dataIndex: 'catId',
            title: intl.formatMessage({ id: 'post.list.catSel' }),
            valueType: 'select',
            valueEnum: { ...cats },
          },
          actions: {
            cardActionProps: 'extra',
            render: (_text, row) => [
              <Button
                type="link"
                onClick={() => {
                  router.push({
                    pathname: '/admin/post/edit/[id]',
                    query: { id: row.id },
                  });
                }}
                key="link"
              >
                <FormattedMessage id="form.edit"></FormattedMessage>
              </Button>,
              <Popconfirm
                key={'form.delete'}
                title={intl.formatMessage({ id: 'form.delete' })}
                description={intl.formatMessage({ id: 'delete.confirm' })}
                onConfirm={() => {
                  handleDelete(row.id);
                }}
                okText={intl.formatMessage({ id: 'form.ok' })}
                cancelText={intl.formatMessage({ id: 'form.close' })}
              >
                <Button danger type="link">
                  <FormattedMessage id="form.delete" />
                </Button>
              </Popconfirm>,
            ],
          },
        }}
        request={async (params = {} as Record<string, any>) => {
          return requestMsg<Data>('/api/post/list', {
            method: 'post',
            data: {
              page: params.current,
              size: params.pageSize,
              catId: params.catId ? parseInt(params.catId) : undefined,
              title: params.title,
            },
            lang,
          }).then((ret) => {
            return Promise.resolve({
              ...ret,
              data: ret.post,
            });
          });
        }}
        search={{}}
        toolBarRender={() => {
          return [
            <Button
              key="3"
              type="primary"
              onClick={() => {
                router.push({
                  pathname: '/admin/post/edit/0',
                });
              }}
            >
              <FormattedMessage id="form.new"></FormattedMessage>
            </Button>,
          ];
        }}
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: false,
        }}
      ></ProList>
    </>
  );
}
Index.Layout = AdminLayout;
